package com.bytenerd.jianmu.aop;

import com.bytenerd.jianmu.annotation.AuthCheck;
import com.bytenerd.jianmu.exception.BusinessException;
import com.bytenerd.jianmu.exception.ErrorCode;
import com.bytenerd.jianmu.model.entity.User;
import com.bytenerd.jianmu.model.enums.RoleEnum;
import com.bytenerd.jianmu.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import static com.bytenerd.jianmu.constant.UserConstant.USER_LOGIN_STATUS;

@Aspect
@Component
public class AuthInterceptor {
    @Resource
    private UserService userService;

    /**
     * 拦截器
     * @param joinPoint
     * @param authCheck
     * @return
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        RequestAttributes RequestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes)RequestAttributes).getRequest();
        // 获取当前登录用户
        User user = (User)request.getSession().getAttribute(USER_LOGIN_STATUS);
        RoleEnum mustRoleEnum = RoleEnum.getByValue(mustRole);
        // 不需要权限，直接放行
        if(mustRoleEnum == null){
            return joinPoint.proceed();
        }
        // 以下代码必须有某个权限才能通过
        RoleEnum userRoleEnum = RoleEnum.getByValue(user.getRole());
        // 没有权限直接拒接
        if(userRoleEnum == null){
            throw new BusinessException(ErrorCode.NOT_AUTH_ERROR);
        }
        // 要求必须有管理员权限
        if(RoleEnum.ADMIN.equals(mustRoleEnum)&&!RoleEnum.ADMIN.equals(userRoleEnum)){
            throw new BusinessException(ErrorCode.NOT_AUTH_ERROR);
        }
        if(RoleEnum.VIP.equals(mustRoleEnum)&&!RoleEnum.VIP.equals(userRoleEnum)){
            throw new BusinessException(ErrorCode.NOT_AUTH_ERROR,"VIP内容");
        }
        return joinPoint.proceed();
    }
}
